﻿#include "Texture2D.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>

namespace DYGraphics
{
	Texture2D::Texture2D(): mID(-1), mWidth(1), mHeight(1), mData(nullptr), 
		mFormat(TextureFormat::RGBA),
		mWrapMode(TextureWrapMode::ClampToBorder),
		mFilterMode(TextureFilterMode::Linear) {}

	Texture2D::Texture2D(int width, int height) : mWidth(width), mHeight(height), mID(-1), mData(nullptr),
		mFormat(TextureFormat::RGBA),
		mWrapMode(TextureWrapMode::ClampToBorder),
		mFilterMode(TextureFilterMode::Linear) {}

	Texture2D::Texture2D(int width, int height, TextureFormat format) : mWidth(width), mHeight(height), mFormat(format), mID(-1), mData(nullptr),
		mWrapMode(TextureWrapMode::ClampToBorder),
		mFilterMode(TextureFilterMode::Linear) {}

	Texture2D::~Texture2D()
	{
		if (mID != -1)
		{
			glDeleteTextures(1, &mID);
			mID = -1;
		}

		if (mData != nullptr)
		{
			delete[] mData;
			mData = nullptr;
		}
	}

	void Texture2D::Apply(bool pKeepData)
	{
		// 生成纹理
		glGenTextures(1, &mID);
	    // 绑定纹理
		glBindTexture(GL_TEXTURE_2D, mID);
		// 设置纹理的参数
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (int)mWrapMode);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (int)mWrapMode);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (int)mFilterMode);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (int)mFilterMode);
		// 上传数据
		glTexImage2D(GL_TEXTURE_2D, 0, (int)mFormat, mWidth, mHeight, 0, (int)mFormat, GL_UNSIGNED_BYTE, mData);

		// 解除纹理的绑定
		glBindTexture(GL_TEXTURE_2D, 0);

		if (!pKeepData)
		{
			delete[] mData;
			mData = nullptr;
		}
	}

	unsigned int Texture2D::GetPixelSize() const
	{
		switch (mFormat)
		{
		case DYGraphics::TextureFormat::RGBA:
			return 32;
		case DYGraphics::TextureFormat::RGB:
			return 24;
		default:
			return 32;
		}
	}
}